import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Button } from '@kernelproxy/ui';
import { useLanguage, useLocalizedLink } from '@kernelproxy/i18n';
import { authService } from '../services/auth';
import { useAuth } from '../contexts/AuthContext';
import { Github, Mail, Lock, Eye, EyeOff, Shield } from 'lucide-react';
import LoadingBar from '../components/LoadingBar';

const Login = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [twoFactorCode, setTwoFactorCode] = useState('');
  const [challengeId, setChallengeId] = useState('');
  const [step, setStep] = useState<'login' | '2fa'>('login');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const { t, language } = useLanguage();
  const { getLink } = useLocalizedLink();
  const navigate = useNavigate();
  const auth = useAuth();

  // Step 1: Login with email and password
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    try {
      const result = await authService.loginWithEmailPassword(email, password);

      if (result.success) {
        if (result.requires2FA) {
          // User has 2FA enabled, create challenge
          const challengeResult = await authService.create2FAChallenge();
          if (challengeResult.success && challengeResult.challenge) {
            setChallengeId(challengeResult.challenge.$id);
            setStep('2fa');
          } else {
            setError(language === 'zh-CN' ? '创建2FA验证失败' : 'Failed to create 2FA challenge');
          }
        } else {
          // No 2FA, login complete
          await auth.checkAuth();
          navigate(getLink('/dashboard'));
        }
      }
    } catch (err: any) {
      console.error('Login error:', err);
      if (err.message?.includes('Invalid credentials') || err.message?.includes('Invalid email or password')) {
        setError(language === 'zh-CN' ? '邮箱或密码错误' : 'Invalid email or password');
      } else if (err.message?.includes('not found')) {
        setError(language === 'zh-CN' ? '该邮箱未注册' : 'Email not registered');
      } else {
        setError(err.message || (language === 'zh-CN' ? '登录失败，请重试' : 'Login failed. Please try again.'));
      }
    } finally {
      setLoading(false);
    }
  };

  // Step 2: Verify 2FA code
  const handleVerify2FA = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!challengeId) {
      setError(language === 'zh-CN' ? '无效的2FA验证' : 'Invalid 2FA challenge');
      return;
    }

    setError('');
    setLoading(true);

    try {
      const result = await authService.verify2FALogin(challengeId, twoFactorCode);

      if (result.success) {
        // 2FA verification successful
        await auth.checkAuth();
        navigate(getLink('/dashboard'));
      }
    } catch (err: any) {
      console.error('2FA verification error:', err);
      if (err.message?.includes('Invalid token') || err.message?.includes('invalid secret')) {
        setError(language === 'zh-CN' ? '验证码错误或已过期' : 'Invalid or expired code');
      } else {
        setError(err.message || (language === 'zh-CN' ? '验证失败，请重试' : 'Verification failed. Please try again.'));
      }
    } finally {
      setLoading(false);
    }
  };

  // Go back to login step
  const handleBackToLogin = () => {
    setStep('login');
    setTwoFactorCode('');
    setChallengeId('');
    setError('');
  };

  const handleOAuthLogin = async (provider: 'google' | 'github') => {
    setError('');
    setLoading(true);
    
    try {
      await authService.oauthLogin(provider);
      // OAuth will redirect, so no need to handle success here
    } catch (err) {
      setError(language === 'zh-CN' ? '第三方登录失败' : 'OAuth login failed');
      setLoading(false);
    }
  };

  return (
    <>
      <LoadingBar loading={loading} />
      <div className="h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center px-4 sm:px-6 lg:px-8 transition-colors duration-300">
        <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <a href="https://kernelproxy.com" className="inline-flex items-center justify-center">
            <span className="text-3xl font-bold text-[#00d4ff]">kernel</span>
            <span className="text-3xl font-bold text-[#0f1c3f] dark:text-white">Proxy</span>
          </a>
          <h2 className="mt-6 text-3xl font-bold text-gray-900 dark:text-white">
            {t('login.title')}
          </h2>
          <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
            {t('login.or')}{' '}
            <Link to={getLink('/register')} className="font-medium text-[#00d4ff] hover:text-[#0f1c3f] dark:hover:text-[#00d4ff]/80">
              {t('login.registerLink')}
            </Link>
          </p>
        </div>
        
        <div className="bg-white dark:bg-gray-800 py-8 px-4 shadow-lg sm:rounded-lg sm:px-10 transition-colors duration-300">
          {error && (
            <div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md">
              <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
            </div>
          )}

          {/* Step 1: Email and Password Login */}
          {step === 'login' && (
            <form className="space-y-5" onSubmit={handleLogin}>
              <div>
                <label htmlFor="email" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                  {language === 'zh-CN' ? '邮箱地址' : 'Email Address'}
                </label>
                <div className="mt-1 relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Mail className="h-5 w-5 text-gray-400" />
                  </div>
                  <input 
                    id="email" 
                    name="email" 
                    type="email" 
                    autoComplete="email" 
                    required 
                    value={email} 
                    onChange={e => setEmail(e.target.value)} 
                    placeholder={language === 'zh-CN' ? '输入您的邮箱' : 'Enter your email'}
                    className="appearance-none block w-full pl-10 px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-[#00d4ff] focus:border-[#00d4ff] transition-colors duration-300" 
                  />
                </div>
              </div>

              <div>
                <label htmlFor="password" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                  {language === 'zh-CN' ? '密码' : 'Password'}
                </label>
                <div className="mt-1 relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Lock className="h-5 w-5 text-gray-400" />
                  </div>
                  <input 
                    id="password" 
                    name="password" 
                    type={showPassword ? 'text' : 'password'}
                    autoComplete="current-password" 
                    required 
                    value={password} 
                    onChange={e => setPassword(e.target.value)} 
                    placeholder={language === 'zh-CN' ? '输入您的密码' : 'Enter your password'}
                    className="appearance-none block w-full pl-10 pr-10 px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-[#00d4ff] focus:border-[#00d4ff] transition-colors duration-300" 
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute inset-y-0 right-0 pr-3 flex items-center"
                  >
                    {showPassword ? (
                      <EyeOff className="h-5 w-5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300" />
                    ) : (
                      <Eye className="h-5 w-5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300" />
                    )}
                  </button>
                </div>
              </div>

              <div className="flex items-center justify-between">
                <div className="text-sm">
                  <Link to={getLink('/forgot-password')} className="font-medium text-[#00d4ff] hover:text-[#0f1c3f] dark:hover:text-[#00d4ff]/80">
                    {language === 'zh-CN' ? '忘记密码？' : 'Forgot password?'}
                  </Link>
                </div>
              </div>

              <div>
                <Button type="submit" fullWidth variant="gradient" disabled={loading}>
                  {loading 
                    ? (language === 'zh-CN' ? '登录中...' : 'Signing in...') 
                    : (language === 'zh-CN' ? '登录' : 'Sign In')}
                </Button>
              </div>
            </form>
          )}

          {/* Step 2: 2FA Verification */}
          {step === '2fa' && (
            <div>
              <button
                onClick={handleBackToLogin}
                className="mb-4 flex items-center text-sm text-gray-600 dark:text-gray-400 hover:text-[#00d4ff] transition-colors"
              >
                <Shield className="w-4 h-4 mr-1" />
                {language === 'zh-CN' ? '返回登录' : 'Back to login'}
              </button>

              <div className="mb-4 p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-md">
                <p className="text-sm text-blue-600 dark:text-blue-400 font-medium mb-1">
                  {language === 'zh-CN' ? '需要双因素验证' : 'Two-Factor Authentication Required'}
                </p>
                <p className="text-xs text-blue-500 dark:text-blue-500">
                  {language === 'zh-CN' 
                    ? '请输入您的验证器应用程序中的6位验证码' 
                    : 'Please enter the 6-digit code from your authenticator app'}
                </p>
              </div>

              <form className="space-y-5" onSubmit={handleVerify2FA}>
                <div>
                  <label htmlFor="twoFactorCode" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    {language === 'zh-CN' ? '验证码' : 'Verification Code'}
                  </label>
                  <input 
                    id="twoFactorCode" 
                    name="twoFactorCode" 
                    type="text" 
                    autoComplete="one-time-code"
                    required 
                    value={twoFactorCode} 
                    onChange={e => setTwoFactorCode(e.target.value.replace(/\D/g, '').slice(0, 6))} 
                    placeholder={language === 'zh-CN' ? '输入6位验证码' : 'Enter 6-digit code'}
                    maxLength={6}
                    className="w-full appearance-none block px-4 py-2.5 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-[#00d4ff] focus:border-[#00d4ff] transition-colors duration-300 text-center text-2xl tracking-widest font-mono placeholder:text-lg placeholder:tracking-normal" 
                  />
                </div>

                <div>
                  <Button type="submit" fullWidth variant="gradient" disabled={loading || twoFactorCode.length !== 6}>
                    {loading 
                      ? (language === 'zh-CN' ? '验证中...' : 'Verifying...') 
                      : (language === 'zh-CN' ? '验证并登录' : 'Verify & Login')}
                  </Button>
                </div>
              </form>
            </div>
          )}

          {/* Divider */}
          <div className="relative my-6">
            <div className="absolute inset-0 flex items-center">
              <div className="w-full border-t border-gray-300 dark:border-gray-600"></div>
            </div>
            <div className="relative flex justify-center text-sm">
              <span className="px-2 bg-white dark:bg-gray-800 text-gray-500 dark:text-gray-400">
                {language === 'zh-CN' ? '或继续使用' : 'Or continue with'}
              </span>
            </div>
          </div>

          {/* OAuth Login Buttons */}
          <div className="space-y-3 mb-6">
            <button
              type="button"
              onClick={() => handleOAuthLogin('google')}
              disabled={loading}
              className="w-full flex items-center justify-center gap-3 px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm bg-white dark:bg-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-300"
            >
              <svg className="w-5 h-5" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
                <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
                <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
                <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
              </svg>
              {language === 'zh-CN' ? 'Google' : 'Google'}
            </button>

            <button
              type="button"
              onClick={() => handleOAuthLogin('github')}
              disabled={loading}
              className="w-full flex items-center justify-center gap-3 px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm bg-white dark:bg-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-300"
            >
              <Github className="w-5 h-5" />
              {language === 'zh-CN' ? 'GitHub' : 'GitHub'}
            </button>
          </div>

          {/* Terms and Privacy Links */}
          <div className="mt-6 text-center text-sm text-gray-600 dark:text-gray-400">
            <span>{language === 'zh-CN' ? '登录即表示您同意我们的' : 'By logging in, you agree to our'} </span>
            <Link 
              to={getLink('/terms-of-service')} 
              className="text-[#00d4ff] hover:underline font-medium"
            >
              {language === 'zh-CN' ? '服务条款' : 'Terms of Service'}
            </Link>
            <span> {language === 'zh-CN' ? '和' : 'and'} </span>
            <Link 
              to={getLink('/privacy-policy')} 
              className="text-[#00d4ff] hover:underline font-medium"
            >
              {language === 'zh-CN' ? '隐私政策' : 'Privacy Policy'}
            </Link>
          </div>
        </div>
      </div>
    </div>
    </>
  );
};

export default Login;
